/**
 * 
 */
package com.ekingstar.framework.util;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 *
 */
public final class UrlUtils {
    //~ Constructors ===================================================================================================

    private UrlUtils() {
    }

    //~ Methods ========================================================================================================

    /**
     * Obtains the full URL the client used to make the request.<p>Note that the server port will not be shown
     * if it is the default server port for HTTP or HTTPS (ie 80 and 443 respectively).</p>
     *
     * @return the full URL
     */
    private static String buildFullRequestUrl(String scheme, String serverName, int serverPort, String contextPath,
        String requestUrl, String servletPath, String requestURI, String pathInfo, String queryString) {

        boolean includePort = true;

        if ("http".equals(scheme.toLowerCase()) && (serverPort == 80)) {
            includePort = false;
        }

        if ("https".equals(scheme.toLowerCase()) && (serverPort == 443)) {
            includePort = false;
        }

        return scheme + "://" + serverName + ((includePort) ? (":" + serverPort) : "") + contextPath
        + buildRequestUrl(servletPath, requestURI, contextPath, pathInfo, queryString);
    }

    /**
     * Obtains the web application-specific fragment of the URL.
     *
     * @return the URL, excluding any server name, context path or servlet path
     */
    private static String buildRequestUrl(String servletPath, String requestURI, String contextPath, String pathInfo,
        String queryString) {

        String uri = servletPath;

        if (uri == null) {
            uri = requestURI;
            uri = uri.substring(contextPath.length());
        }

        return uri + ((pathInfo == null) ? "" : pathInfo) + ((queryString == null) ? "" : ("?" + queryString));
    }

    public static String getFullRequestUrl(HttpServletRequest r) {
        return buildFullRequestUrl(r.getScheme(), r.getServerName(), r.getServerPort(), r.getContextPath(),
            r.getRequestURL().toString(), r.getServletPath(), r.getRequestURI(), r.getPathInfo(), r.getQueryString());
    }

    public static String getRequestUrl(HttpServletRequest r) {
        return buildRequestUrl(r.getServletPath(), r.getRequestURI(), r.getContextPath(), r.getPathInfo(),
            r.getQueryString());
    }

    


}
